#include "evm_module_eventbus.h"


static int eventHandler(evm_t *e, evm_event_msg_t *msg)
{
    evm_val_t *eventbus = evm_prop_get(e, &e->root, "eventbus", 0);
    evm_val_t *emit = evm_prop_get(e, eventbus, "emit", 0);

    evm_val_t *event = evm_heap_string_create(e, msg->event, 0);
    if(event == NULL)
        return -1;

    if(evm_is_script(emit) ){
		event_cb *handler = msg->cb;
		if(handler == NULL){
			evm_val_t args[2];
			args[0] = evm_mk_number(msg->id);
			args[1] = *event;
			evm_run_callback(e, emit, eventbus, args, 2);
		}else{
			evm_val_t args[3];
			args[0] = evm_mk_number(msg->id);
			args[1] = *event;
			args[2] = handler(e, msg->data);
			evm_run_callback(e, emit, eventbus, args, 3);
		}

        if(msg->free != NULL){
            msg->free(msg->data);
        }
    }
    return 0;
}

void evm_eventbus_poll(evm_t *e){
    evm_event_msg_t msg;
    while(evm_module_msg_get(&msg,0) == 0){
        eventHandler(e, &msg);
    }
}

/**
 * @brief 获取对象地址
 */
static evm_val_t evm_module_eventbus_id(evm_t * e, evm_val_t * p, int argc, evm_val_t * v){
    EVM_UNUSED(e);
    EVM_UNUSED(p);

    if(argc != 1)
        return EVM_VAL_UNDEFINED;

    return evm_mk_number(evm_2_intptr(v));
}

int evm_module_eventbus(evm_t *e){
    if(evm_module_eventbus_init() != 0)
        return -1;

    evm_cffi_t funcs[] = {
        {NULL, 0, NULL}
    };

    evm_builtin_t builtin[] = {
        {"id", evm_mk_native((intptr_t)evm_module_eventbus_id)},
        {NULL, EVM_VAL_UNDEFINED}
    };

    evm_module_effi_create(e, "@native.eventbus", funcs , builtin);
    if(e->err != ec_ok)
        return -1;
    return 0;
}
